// 文件类型  上传   转为byte[]
export function file2Uint8Array(file) {
  return new Promise((resolve) => {
    //file 为上传文件
    const reader = new FileReader()
    reader.readAsArrayBuffer(file)
    reader.onload = function () {
      const bytes = new Uint8Array(this.result)
      const bytesArray = []
      for (let i = 0; i < bytes.length; i++) {
        bytesArray.push(bytes[i])
      }
      resolve(bytesArray)
    }
  })
}
// 下载文件方法
export function downloadDoc(content, filename, type) {
  const eleLink = document.createElement("a")
  eleLink.download = filename
  eleLink.style.display = "none"

  const res = this.dataURLtoBlob(content, type)
  eleLink.href = URL.createObjectURL(res)
  // 自动触发点击
  document.body.appendChild(eleLink)
  eleLink.click()
  // 然后移除
  URL.revokeObjectURL(eleLink.href)
  document.body.removeChild(eleLink)
}

//base64 转换 blob
export function dataURLtoBlob(dataurl, type) {
  var bstr = window.atob(dataurl)
  var n = bstr.length
  var u8arr = new Uint8Array(n)
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n)
  }
  var blob
  if (type) {
    blob = new Blob([u8arr], { type: type })
  } else {
    //type是undefined  默认下载xlsx
    blob = new Blob([u8arr], {
      type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
    })
  }
  return blob
}
